import requests
import json
import time
import os
##cron: 13 9 * * *
##new Env("美的")
try:
    from notify import send
except ImportError:
    print("❌ 无法导入青龙通知模块，将使用控制台输出")

def send_notification(title, content):
    """
    发送通知函数
    """
    try:
        send(title, content)
        print(f"✅ 通知发送成功: {title}")
    except Exception as e:
        print(f"❌ 通知发送失败: {str(e)}")
        print(f"📢 通知内容: {title} - {content}")

def get_user_info_from_env():
    """
    从青龙环境变量获取用户信息
    格式: uid#openId#unionId
    """
    user_info_str = os.environ.get('MEIDA', '')
    if not user_info_str:
        error_msg = "❌ 未找到环境变量 MEIDA"
        print(error_msg)
        send_notification("美的签到失败", error_msg)
        return None, None, None
    
    try:
        parts = user_info_str.split('#')
        if len(parts) != 3:
            error_msg = f"❌ 环境变量格式错误，应为 uid#openId#unionId，当前: {user_info_str}"
            print(error_msg)
            send_notification("美的签到失败", error_msg)
            return None, None, None
        
        uid, openId, unionId = parts
        print("✅ 成功从环境变量获取用户信息")
        return uid.strip(), openId.strip(), unionId.strip()
    
    except Exception as e:
        error_msg = f"❌ 解析环境变量失败: {str(e)}"
        print(error_msg)
        send_notification("美的签到失败", error_msg)
        return None, None, None

def midea_sign_in():
    """
    美的签到函数
    """
    # 从环境变量获取用户信息
    uid, openId, unionId = get_user_info_from_env()
    if not all([uid, openId, unionId]):
        error_msg = "❌ 用户信息不完整，无法签到"
        print(error_msg)
        send_notification("美的签到失败", error_msg)
        return None

    url = "https://weixin.midea.com/mscp_mscp/api/cms_api/activity-center-im-service/im-svr/im/game/page/sign"
    
    cookies = {
        "im_token": "43D9874076FCCB10FE3E9083EED7A7FE",
    }

    headers = {
        "Host": "weixin.midea.com",
        "Connection": "keep-alive",
        "appId": "QLZZ9Fr7w2to",
        "sec-ch-ua-platform": "\"Android\"",
        "timeStamp": str(int(time.time() * 1000)),  # 动态时间戳
        "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Android WebView\";v=\"138\"",
        "sec-ch-ua-mobile": "?1",
        "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380215 MMWEBSDK/20221011 MMWEBID/9222 MicroMessenger/8.0.30.2260(0x28001E3B) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 miniProgram/wx49a622805968d156",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json",
        "apiKey": "3660663068894a0d9fea574c2673f3c0",
        "vcode": "922836819ff32fda0f7fffbf47351c7f",
        "Origin": "https://weixin.midea.com",
        "X-Requested-With": "com.tencent.mm",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://weixin.midea.com/apps/h5-pro-wx-interaction-marketing/",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }

    data = {
        "headParams": {
            "language": "CN",
            "originSystem": "MCSP",
            "timeZone": "",
            "userCode": "",
            "tenantCode": "",
            "userKey": "TEST_",
            "transactionId": ""
        },
        "pagination": None,
        "restParams": {
            "gameId": 28,
            "actvId": "401670810827462661",
            "rootCode": "DJ",
            "appCode": "DJ_WX",
            "imUserId": "465262491229018116",
            "uid": uid,
            "openId": openId,
            "unionId": unionId
        }
    }

    try:
        print("🔄 正在发送签到请求...")
        response = requests.post(url, headers=headers, cookies=cookies, data=json.dumps(data))
        
        # 检查响应状态
        if response.status_code != 200:
            error_msg = f"❌ 请求失败，状态码: {response.status_code}"
            print(error_msg)
            send_notification("美的签到失败", error_msg)
            return None
            
        result = response.json()
        
        # 检查响应结构
        if not isinstance(result, dict):
            error_msg = "❌ 响应格式错误"
            print(error_msg)
            send_notification("美的签到失败", error_msg)
            return None
            
        code = result.get("code")
        msg = result.get("msg", "")
        
        # 处理重复签到情况
        if "已签到" in msg or "明日" in msg or "重复" in msg:
            notification_msg = "⏰ 今日已签到，请明日再来！"
            print(notification_msg)
            print(f"💡 提示信息: {msg}")
            send_notification("美的签到提醒", notification_msg)
            return result
            
        if code == "000000":
            sign_data = result.get("data", {})
            if sign_data.get("result"):
                reward_info = sign_data.get("dailyRewardInfo", {})
                success_msg = f"✅ 签到成功！\n连续签到: {sign_data.get('consecutiveDays', '0')} 天\n获得奖励: {reward_info.get('name', '未知奖励')}\n奖励积分: {reward_info.get('points', '0')}"
                print(success_msg)
                
                # 发送成功通知
                send_notification("美的签到成功", success_msg)
                
                # 记录签到成功日志
                log_sign_success(sign_data)
            else:
                error_msg = f"❌ 签到失败\n错误信息: {result.get('msg', '未知错误')}"
                print(error_msg)
                send_notification("美的签到失败", error_msg)
        else:
            error_msg = f"❌ 请求失败\n错误代码: {code}\n错误信息: {msg}"
            print(error_msg)
            send_notification("美的签到失败", error_msg)
            
        return result
        
    except requests.exceptions.RequestException as e:
        error_msg = f"❌ 网络请求异常: {str(e)}"
        print(error_msg)
        send_notification("美的签到失败", error_msg)
        return None
    except json.JSONDecodeError as e:
        error_msg = f"❌ JSON解析异常: {str(e)}"
        print(error_msg)
        send_notification("美的签到失败", error_msg)
        return None
    except Exception as e:
        error_msg = f"❌ 未知异常: {str(e)}"
        print(error_msg)
        send_notification("美的签到失败", error_msg)
        return None

def log_sign_success(sign_data):
    """
    记录签到成功日志
    """
    try:
        consecutive_days = sign_data.get('consecutiveDays', '0')
        reward_info = sign_data.get('dailyRewardInfo', {})
        reward_name = reward_info.get('name', '未知奖励')
        points = reward_info.get('points', '0')
        
        log_message = f"""
📅 签到成功记录
├── 连续签到: {consecutive_days} 天
├── 获得奖励: {reward_name}
└── 积分数量: {points}
        """
        print(log_message)
        
    except Exception as e:
        print(f"⚠️ 记录日志时发生错误: {str(e)}")

def check_environment():
    """
    检查环境变量设置
    """
    user_info = os.environ.get('MEIDA', '')
    if not user_info:
        error_msg = "❌ 环境变量 MEIDA 未设置\n💡 请在青龙面板中设置环境变量，格式: uid#openId#unionId"
        print(error_msg)
        send_notification("美的签到配置错误", error_msg)
        return False
    
    parts = user_info.split('#')
    if len(parts) != 3:
        error_msg = f"❌ 环境变量格式错误\n💡 正确格式: uid#openId#unionId\n💡 当前格式: {user_info}"
        print(error_msg)
        send_notification("美的签到配置错误", error_msg)
        return False
    
    print("✅ 环境变量检查通过")
    return True

def main():
    """
    主函数
    """
    print("=" * 50)
    print("🤖 美的自动签到脚本")
    print("=" * 50)
    
    # 检查环境变量
    if not check_environment():
        return
    
    # 执行签到
    result = midea_sign_in()
    
    if result:
        print("\n✅ 签到流程完成")
    else:
        print("\n❌ 签到流程失败")

if __name__ == "__main__":
    main()